package com.lewis.system.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.lewis.core.annotation.Log;
import com.lewis.core.base.controller.BaseController;
import com.lewis.core.base.domain.BaseResult;
import com.lewis.core.base.domain.entity.SysMenu;
import com.lewis.core.base.domain.model.LoginUser;
import com.lewis.core.constant.UserConstants;
import com.lewis.core.enums.BusinessType;
import com.lewis.core.utils.MapUtil;
import com.lewis.core.utils.SecurityUtil;
import com.lewis.core.utils.ServletUtil;
import com.lewis.core.utils.StringUtil;
import com.lewis.system.service.ISysMenuService;
import com.lewis.system.web.service.TokenService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

/**
 * 菜单信息
 *
 * @author Lewis
 */
@Api(tags = "登录验证")
@RestController
@RequestMapping("/system/menu")
public class SysMenuController extends BaseController {

    @Resource
    private ISysMenuService sysMenuService;

    @Resource
    private TokenService tokenService;

    @ApiOperation(value = "获取菜单列表", notes = "获取菜单列表")
    @GetMapping("/list")
    public BaseResult list(SysMenu menu) {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtil.getRequest());
        Long userId = loginUser.getUser().getId();
        return ok().setData(sysMenuService.selectMenuList(menu, userId));
    }

    @ApiOperation(value = "根据菜单编号获取详细信息", notes = "根据菜单编号获取详细信息")
    @GetMapping(value = "/{id}")
    public BaseResult getInfo(@PathVariable Long id) {
        return ok().setData(sysMenuService.getById(id));
    }

    @ApiOperation(value = "获取菜单下拉树列表", notes = "获取菜单下拉树列表")
    @GetMapping("/treeselect")
    public BaseResult treeselect(SysMenu menu) {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtil.getRequest());
        Long userId = loginUser.getUser().getId();
        return ok().setData(sysMenuService.buildMenuTreeSelect(sysMenuService.selectMenuList(menu, userId)));
    }

    @ApiOperation(value = "加载对应角色菜单列表树", notes = "加载对应角色菜单列表树")
    @GetMapping(value = "/roleMenuTreeselect/{roleId}")
    public Object roleMenuTreeselect(@PathVariable("roleId") Long roleId) {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtil.getRequest());
        List<SysMenu> menus = sysMenuService.selectMenuList(loginUser.getUser().getId());
        BaseResult ok = ok();
        Map ajax = MapUtil.object2MapByReflect(ok);
        ajax.put("menus" , sysMenuService.buildMenuTreeSelect(menus));
        return ajax;
    }

    @ApiOperation(value = "新增菜单", notes = "新增菜单")
    @Log(title = "菜单管理" , businessType = BusinessType.INSERT)
    @PostMapping
    public BaseResult add(@Validated @RequestBody SysMenu menu) {
        if (UserConstants.NOT_UNIQUE.equals(sysMenuService.checkMenuNameUnique(menu))) {
            return fail().setMsg("新增菜单'" + menu.getMenuName() + "'失败，菜单名称已存在");
        } else if (UserConstants.YES_FRAME.equals(menu.getIsFrame()) && !StringUtil.isHttp(menu.getPath())) {
            return fail().setMsg("新增菜单'" + menu.getMenuName() + "'失败，地址必须以http(s)://开头");
        }
        menu.setCreateBy(SecurityUtil.getUsername());
        return getResult(sysMenuService.save(menu));
    }

    @ApiOperation(value = "修改菜单", notes = "修改菜单")
    @Log(title = "菜单管理" , businessType = BusinessType.UPDATE)
    @PutMapping
    public BaseResult edit(@Validated @RequestBody SysMenu menu) {
        if (UserConstants.NOT_UNIQUE.equals(sysMenuService.checkMenuNameUnique(menu))) {
            return fail().setMsg("修改菜单'" + menu.getMenuName() + "'失败，菜单名称已存在");
        } else if (UserConstants.YES_FRAME.equals(menu.getIsFrame()) && !StringUtil.isHttp(menu.getPath())) {
            return fail().setMsg("修改菜单'" + menu.getMenuName() + "'失败，地址必须以http(s)://开头");
        } else if (menu.getId().equals(menu.getParentId())) {
            return fail().setMsg("修改菜单'" + menu.getMenuName() + "'失败，上级菜单不能选择自己");
        }
        menu.setUpdateBy(SecurityUtil.getUsername());
        return getResult(sysMenuService.updateById(menu));
    }

    @ApiOperation(value = "删除菜单", notes = "删除菜单")
    @Log(title = "菜单管理" , businessType = BusinessType.DELETE)
    @DeleteMapping("/{id}")
    public BaseResult remove(@PathVariable("id") Long id) {

        if (sysMenuService.getOne(
                new LambdaQueryWrapper<SysMenu>()
                        .eq(SysMenu::getParentId, id)
                        .last("limit 1")) != null
        ) {
            return fail().setMsg("存在子菜单,不允许删除");
        }
        return getResult(sysMenuService.removeById(id));
    }
}